#!/bin/bash

# 引入配置文件
source config.sh

# 日志文件路径
LOG_FILE="$LOG_DIR/backup.log"

# 创建日志目录
mkdir -p $LOG_DIR
touch $LOG_FILE

# 日志记录函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | sudo tee -a $LOG_FILE
}

# 错误处理函数
error_exit() {
    log "ERROR: $1"
    exit 1
}

# 备份目录
mkdir -p $BACKUP_DIR

# 1. 备份 MySQL 数据库
backup_database() {
    local BACKUP_FILE="$BACKUP_DIR/db-backup-$(date +%F).sql"
    log "Backing up MySQL database..."
    mysqldump -u $DB_USER -p$DB_PASS $DB_NAME > $BACKUP_FILE || error_exit "Failed to backup database."
    sudo chmod 644 $BACKUP_FILE
    log "Database backup completed: $BACKUP_FILE"
}

# 2. 备份项目文件
backup_project() {
    local BACKUP_FILE="$BACKUP_DIR/project-backup-$(date +%F).tar.gz"
    log "Backing up project files..."
    tar -czvf $BACKUP_FILE $PROJECT_DIR > /dev/null || error_exit "Failed to backup project files."
    sudo chmod 644 $BACKUP_FILE
    log "Project backup completed: $BACKUP_FILE"
}

# 3. 清理超过 7 天的旧备份
clean_old_backups() {
    log "Cleaning backups older than 7 days..."
    find $BACKUP_DIR -type f -mtime +7 -name "*.sql" -exec rm -f {} \;
    find $BACKUP_DIR -type f -mtime +7 -name "*.tar.gz" -exec rm -f {} \;
    log "Old backups cleaned."
}

# 主逻辑
if [ "$1" == "db" ]; then
    backup_database
elif [ "$1" == "project" ]; then
    backup_project
elif [ "$1" == "all" ]; then
    backup_database
    backup_project
else
    echo "Usage: $0 [db|project|all]"
    exit 1
fi

# 清理超过 7 天的旧备份
clean_old_backups

log "Backup process completed successfully!"